package com.turnengine.client.local.player.command;

import com.javabi.command.IExecutableCommand;
import com.javabi.command.IExecutableCommandResponse;
import com.javabi.command.serializer.AbstractCommandDataSerializer;
import com.javabi.common.io.data.IDataReader;
import com.javabi.common.io.data.IDataWriter;
import com.turnengine.client.local.player.bean.IPlayer;
import com.turnengine.client.local.player.bean.PlayerSerializer;
import java.io.IOException;

/**
 * The Get Player By Name Data Serializer.
 */
public class GetPlayerByNameDataSerializer extends AbstractCommandDataSerializer<IPlayer> implements IGetPlayerByNameDataSerializer {

	/**
	 * Creates a new Get Player By Name Data Serializer.
	 */
	public GetPlayerByNameDataSerializer() {
		super(GetPlayerByName.COMMAND_ID);
	}

	@Override
	public IPlayer readReturnValue(IDataReader reader) throws IOException {
		IPlayer value = new PlayerSerializer().readObject(reader);
		return value;
	}

	@Override
	public void writeReturnValue(IDataWriter writer, IPlayer value) throws IOException {
		new PlayerSerializer().writeObject(writer, value);
	}

	@Override
	public IExecutableCommand<IPlayer> readRequest(IDataReader reader) throws IOException {

		// Read fields
		long loginId = reader.readLong();
		int instanceId = reader.readInt();
		String name = reader.readString(true);

		// Create object
		GetPlayerByName object = new GetPlayerByName();
		object.setLoginId(loginId);
		object.setInstanceId(instanceId);
		object.setName(name);
		return object;
	}

	@Override
	public void writeRequest(IDataWriter writer, IExecutableCommand<IPlayer> argument) throws IOException {
		GetPlayerByName object = (GetPlayerByName) argument;

		// Get fields
		long loginId = object.getLoginId();
		int instanceId = object.getInstanceId();
		String name = object.getName();

		// Write fields
		writer.writeLong(loginId);
		writer.writeInt(instanceId);
		writer.writeString(name, true);
	}

	@Override
	public IExecutableCommandResponse<IPlayer> newResponse() {
		return new GetPlayerByNameResponse();
	}
}
